<template>
  <a-card>
    <Header :title="'返回'" :subTitle="'优惠券补发'" :hasBackPath="true" @headerBack="$router.back()"></Header>
    <a-spin :spinning="spinning" size="large">
      <a-form-model
        ref="rulesForm"
        :model="form"
        :rules="rules"
        :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 14 }, sm: { span: 17 } }"
      >
        <a-form-model-item label="补发原因" prop="season">
          <a-radio-group v-model="form.season">
            <a-radio :value="1">
              流程申请
            </a-radio>
            <a-radio :value="2">
              自主创建
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item v-if="form.season == 1" label="申请部门" key="flow_id">
          <template>
            <a-select v-model="form.flow_id" style="width: 50%;">
              <a-select-option :value="item.id" v-for="(item, index) in departments" :key="index">
                {{ item.department }}
              </a-select-option>
            </a-select>
            <div style="margin-left: 5%;;width: 45%;display: inline-block;vertical-align: top;line-height: 30px;">
              申请用途：{{usefor}}
            </div>
          </template>
        </a-form-model-item>
        <a-form-model-item class="hidden-title" label="备注" prop="addReason" v-if="form.season == 2" key="addReason">
          <a-textarea v-model="form.addReason" placeholder="请说明补发原因" :maxLength="300" :rows="4"/>
        </a-form-model-item>
        <a-form-model-item label="发放对象" v-if="sendType != 3" required key="sendUser">
          <SendUser :id="id" ref="sendUser" :sendType="sendType" @checkCard="checkCard"
                    @checkFollow="checkFollow"></SendUser>
        </a-form-model-item>
        <a-form-model-item label="补发数量" prop="addNum" v-if="sendType == 3" key="addNum">
          <a-input-number :min="0" style="width: 100%;" placeholder="请输入补发数量" v-model.trim="form.addNum" />
        </a-form-model-item>
        <a-divider/>
        <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary" :disabled="submitFlag" @click="handleSubmit">确认提交</a-button>
          <div style="color: red;">一旦提交成功，优惠券将直接发放生效，请认真确认所填信息！</div>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-card>
</template>
<script>
  import {
    addAndEditCoupon,
    submit,
    printDetails
  } from '@/api/headquartersCoupon/index'
  import SendUser from './components/SendUser'
  import Header from '@/views/box/components/layouts/Header'

  export default {
    components: {
      SendUser,
      Header
    },
    data() {
      return {
        applyUseList: [],
        submitFlag: false,
        spinning: false,
        departments: [],
        showPageVoList: [],
        smstempList: [],
        sendType: '', // 发券类型1微信券2礼券3纸质券
        form: {
          season: 1,
          isCard: 2,
          isFollow: 2,
          flow_id: '',
          applyUse: '',
          department: '',
          addReason: '',
          addNum: ''
        },
        rules: {
          addNum: [
            { required: true, message: '请输入', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                const reg = /^[0-9]*[1-9][0-9]*$/
                if (!value) {
                  callback()
                } else {
                  if (reg.test(value)) {
                    callback()
                  } else {
                    return callback(new Error('请输入正确的格式'))
                  }
                }
              },
              trigger: 'blur'
            }
          ],
          department: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          flow_id: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          applyUse: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          addReason: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          applyTemplateId: [
            { required: true, message: '请选择', trigger: 'change' }
          ]
        }
      }
    },
    computed: {
      id() {
        return this.$route.params.id
      },
      pageId() {
        return this.$route.query.pageId
      },
      usefor() {
        const list = this.departments.filter(e => e.id == this.form.flow_id)
          if (list.length) {
            return list[0].usefor
          } else {
            return ''
          }
      }
    },
    watch: {
      $route(to, from) {
        if (from.path.includes('/box/boxLook/addAndEdit2') || to.path.includes('/box/boxLook/addAndEdit2')) {
        } else {
          this.form = {}
        }
      }
    },
    activated() {
    },
    created() {
      this.getDetails()
    },
    mounted() {
    },
    
    beforeDestory() {
      // window.onbeforeunload = null
    },
    methods: {
      //检测是否有未开卡
      checkCard(v) {
        this.form.isCard = v ? 1 : 2
      },

      //检测是否有未关注
      checkFollow(v) {
        this.form.isFollow = v ? 1 : 2
      },
     
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      },

      // 获取券详情
      getDetails() {
        this.sendType = this.$route.query.sendType
        this.spinning = true
        const data = {
          pageId: this.pageId,
          id: this.id
        }
        addAndEditCoupon(data).then(res => {
          this.spinning = false
          if (res.code === 200) {
            const { oaflows, showPageVoList, smstempList, applyUseList } = res.data
            this.departments = oaflows.records
            this.showPageVoList = showPageVoList
            this.smstempList = smstempList
            this.applyUseList = Object.keys(applyUseList)
          } else {
            this.$message.error(res.msg || res.message)
          }
        }).catch(err => {
          this.spinning = false
        })
      },


      //提交
      handleSubmit() {
        const that = this
        this.$refs.rulesForm.validate(valid => {
          if (valid) {
            const {flow_id, season, addNum, addReason} = this.form
            if (this.sendType != 3) {
              if (!this.$refs.sendUser.checkSendUser()) {
                this.$message.info('请先添加发放对象！')
                return
              }
            }
            this.submitFlag = true
            const list = this.departments.filter(e => e.id == flow_id)
            const data = {
              id: this.id,
              pageId: this.pageId,
              ...this.form,
              flow_id: season == 1 && flow_id ? flow_id : null,
              department: season == 1 && list.length ? list[0].department : null,
              applyUse: this.usefor,
              addNum: this.sendType == 3 ? addNum : null,
              addReason: season == 2 ? addReason : this.usefor
            }
            submit(data).then(res => {
              if (res.code === 200) {
                // this.submitFlag = false
                if (this.sendType == 1) {
                  this.$info({
                    title: '提交成功！消息已发送～',
                    icon: 'none',
                    okText: '返回',
                    closable: false,
                    onOk() {
                      that.$router.go(-1)
                    }
                  })
                } else {
                  this.$confirm({
                    title: '提交成功！',
                    icon: 'none',
                    closable: false,
                    okText: '打印券码',
                    cancelText: '返回',
                    onOk() {
                      const data = {
                        pageId: that.id
                      }
                      printDetails(data).then(res => {
                        if (res.code === 200) {
                          const data = decodeURIComponent(JSON.stringify(res.data))
                          that.$router.push(`/headquarters-coupon/print/1?data=${data}`)
                        } else {
                          that.$message.warning(res.msg || res.message)
                        }
                      })
                    },
                    onCancel() {
                      that.$router.go(-1)
                    }
                  })
                }
              } else {
                this.submitFlag = false
                this.$message.error(res.msg || res.message)
              }
            })

          } else {
            return false
          }
        })
      }
    }
  }
</script>
<style scoped>
  .association-list /deep/ td {
    padding-bottom: 0 !important;
  }

  .hidden-title /deep/ .ant-form-item-label > label {
    visibility: hidden;
  }
</style>
